package blog.service.impl;

import blog.service.thread.ThreadService;
import blog.service.thread.UserThreadLocal;
import blog.dao.mapper.ArticleTagMapper;
import blog.dao.pojo.ArticleTag;
import blog.dao.dos.Archives;
import blog.dao.mapper.ArticleBodyMapper;
import blog.dao.mapper.ArticleMapper;
import blog.dao.pojo.Article;
import blog.dao.pojo.ArticleBody;
import blog.service.*;
import blog.vo.*;
import blog.vo.params.ArticleParam;
import blog.vo.params.PageParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysUserService sysUserService;

    // 最热文章
    @Override
    public Result hotArticles(Integer limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

        // 根据浏览量降序排，只要文章id和title
        wrapper.orderByDesc(Article::getViewCounts);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit "+limit);

        List<Article> articles = articleMapper.selectList(wrapper);

        return Result.success(copyList(articles,false,false));
    }

    // 最新文章
    @Override
    //@Cacheable(value = "lastArticles",keyGenerator = "myKeyGenerator")
    public Result lastArticles(Integer limit) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

        wrapper.orderByDesc(Article::getCreateDate);
        wrapper.select(Article::getId,Article::getTitle);
        wrapper.last("limit "+limit);

        List<Article> articles = articleMapper.selectList(wrapper);

        return Result.success(copyList(articles,false,false));
    }

    // 文章归档
    @Override
    public Result listArchives() {
        List<Archives> listArchives = articleMapper.listArchives();

        return Result.success(listArchives);
    }


    // 显示首页所有文章
    /*@Override
    public Result listArticles(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());

        // 按是否置顶，写作时间降序
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        if (pageParams.getCategoryId() != null) {
            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
        }

        List<Long> articleIdList = new ArrayList<>();

        if (pageParams.getTagId() != null){
            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();

            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);

            for (ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }

            if (articleIdList.size() > 0){
                queryWrapper.in(Article::getId,articleIdList);
            }
        }


        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);

        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();

        return Result.success(copyList(records,true,true));
    }*/

    public Result listArticles(PageParams pageParams){
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());

        IPage<Article> articlesPage = articleMapper.listArticles(page, pageParams.getCategoryId(), pageParams.getTagId(), pageParams.getYear(), pageParams.getMonth());

        List<Article> articles = articlesPage.getRecords();

        return Result.success(copyList(articles,true,true));
    }


    @Autowired
    private ArticleTagMapper articleTagMapper;
    // 发布文章
    @Override
    @Transactional
    public Result publish(ArticleParam articleParam) {

        Article article = new Article();
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setViewCounts(0);
        article.setAuthorId(UserThreadLocal.get().getId());
        article.setBodyId(-1L);
        article.setCategoryId(articleParam.getCategory().getId());
        article.setWeight(0);
        article.setCreateDate(new DateTime().getMillis());
        articleMapper.insert(article);  // 插入文章


        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);  // 插入articleBody,自动生成bodyId


        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);  // 更新bodyId


        List<TagVo> tagVos = articleParam.getTags();
        if (tagVos!=null){
            for (TagVo tagVo:tagVos){
                ArticleTag articleTag = new ArticleTag();

                articleTag.setTagId(tagVo.getId());
                articleTag.setArticleId(article.getId());
                articleTagMapper.insert(articleTag);
            }
        }

        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(article.getId());
        return Result.success(articleVo);
    }



    @Autowired
    private ThreadService threadService;

    // 通过文章id找到文章具体内容
    @Override
    public Result findArticleById(Long id) {

        Article article = articleMapper.selectById(id);

        threadService.updateViewCount(articleMapper,article);  // 线程池开启文章阅读次数

        ArticleVo articleVo = copy(article, true, true, true, true);

        return Result.success(articleVo);
    }

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    // 找到文章所属分类
    private CategoryVo findCategory(Long categoryId) {
        return categoryService.findCategoryById(categoryId);
    }

    // 根据文章id找到
    private ArticleBodyVo findArticleBody(Long articleId) {
        LambdaQueryWrapper<ArticleBody> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleBody::getArticleId,articleId);

        ArticleBody articleBody = articleBodyMapper.selectOne(queryWrapper);

        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }


    // pojo对象转vo对象，复制
    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor){

        ArrayList<ArticleVo> articleVos = new ArrayList<>();

        for (Article record: records){
            articleVos.add(copy(record,isTag,isAuthor,false,false));
        }

        return articleVos;
    }

    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);

        // 将文章发表时间（毫秒L）转换指定格式
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));

        // 显示文章时是否需要显示标签
        if (isTag){
            Long articleId = article.getId();
            articleVo.setTags(tagService.FindTagsByArticled(articleId));
        }

        if (isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserByArticleId(authorId).getNickname());
        }

        if (isBody){
            ArticleBodyVo articleBody = findArticleBody(article.getId());
            articleVo.setBody(articleBody);
        }
        if (isCategory){
            CategoryVo categoryVo = findCategory(article.getCategoryId());
            articleVo.setCategory(categoryVo);
        }

        return articleVo;
    }
}
